home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / answrbok / 2_2.lha / 2_2 / 2_2_sqrt.c next >
Text File  |  1993-08-08  |  966b  |  49 lines

  1. * Copyright (c) 1990 by AT&T Bell Telephone Laboratories, Incorporated. */
  2. * The C++ Answer Book */
  3. * Tony Hansen */
  4. * All rights reserved. */
  5. include <complex.h>
  6. include <math.h>
  7. / determine sqrt of x + yi
  8. omplex sqrt(complex z)
  9.  
  10.    double x = real(z);
  11.    double y = imag(z);
  12.  
  13.    // the easy ones: y == 0
  14.    if (y == 0.0)
  15. if (x < 0.0)
  16.     return complex(0.0, sqrt(-x));
  17.  
  18. else
  19.     return complex(sqrt(x), 0.0);
  20.  
  21.    // almost as easy: x == 0
  22.    if (x == 0.0)
  23. if (y < 0.0)
  24.     {
  25.     double x = sqrt(-y / 2);
  26.     return complex(x, -x);
  27.     }
  28.  
  29. else
  30.     {
  31.     double x = sqrt(y / 2);
  32.     return complex(x, x);
  33.     }
  34.  
  35.    // convert to polar and take the root
  36.    //
  37.    //        2    2  1/2
  38.    // r = ( x  + y )
  39.    //
  40.    // theta = O- = arc tan (y / x)
  41.    //
  42.    //  1/2    1/2
  43.    // z    = r   (cos O-/2 + i sin O-/2)
  44.    double root_r = sqrt(sqrt(x * x + y * y));
  45.    double half_t = atan2(y, x) / 2.0;
  46.    return complex(root_r * cos(half_t),
  47.        root_r * sin(half_t));
  48.  
  49.